import {Component, EventEmitter, OnChanges, OnInit, Output} from "@angular/core";
import {NzNotificationService, UploadFile} from 'ng-zorro-antd';
import {Config} from "../../../../service/config";
import {UserBean} from "../bean/user.bean";
import {HttpServcie} from "../../../../service/http.service";
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import * as moment from 'moment';

@Component({
  selector:'user-add-page',
  templateUrl:'user-add.html',
  styleUrls:['user-add.scss']
})

export class UserAddPage implements OnInit,OnChanges {
  validateForm: FormGroup;
  isSpinning: boolean = false;
  @Output("outPut") outPut = new EventEmitter();
  config: any = Config;
  personalBean: UserBean = new UserBean();//系统类型
  roleTypeList = [];//角色类型集合
  _useroptions = [];  //用户类型
  _cardTypeoption = [];//用户持证类型
  partyList = []; //单位全称集合
  user = JSON.parse(window.localStorage.getItem("user"));
  public partyType = JSON.parse(window.localStorage.getItem("user")).partyType;
  public socialList = []; //社保证明
  public cardType: any = []; //用户持证类型

  constructor(private fb: FormBuilder,
              private httpServcie: HttpServcie,
              private _notification: NzNotificationService) {
  }

  ngOnInit() {

    this.personalBean.type="user";
    //监管单位与非监管单位
    if (this.user.partyType == "4") {
      this.validateForm = this.fb.group({
        userName: [null, [Validators.required, this.userNameCheck]],//用户姓名
        password: [null, [Validators.required]],
        checkPassword: [null, [Validators.required, this.confirmationValidator]],
        userCode: [null, [Validators.required]], //用户名
        cardType: [null, [Validators.nullValidator]],//用户持证类型
        cardTypeNumber: [null, [Validators.nullValidator]],//证件号
        cardNumber: [null, [Validators.required, this.cardNumberCheck]],//身份证号码
        workNumber: [null, [Validators.required]],//工号
        partyId: [null, [Validators.required]],//单位全称
        agree: [null, [Validators.nullValidator]],
        roleTypeId: [null, [Validators.nullValidator]],//角色所属类型
        roleId: [null, [Validators.required]],//角色
        phone: [null, [Validators.required, this.mobileCheck]],
        firstgtshow: [null, [Validators.nullValidator]],
      });


      this._cardTypeoption = [
        {value: '', label: '请选择'},
        {value: '监察A类', label: '监察A类'},
        {value: '监察B类', label: '监察B类'},
        {value: '监管协管员证', label: '监管协管员证'},
        {value: '其他', label: '其他'},
      ];
    }
    else {
      this.validateForm = this.fb.group({
        partyId: [null, [Validators.required]],//单位全称
        userName: [null, [Validators.required, this.userNameCheck]],//用户姓名
        cardNumber: [null, [Validators.required, this.cardNumberCheck]],//身份证号码
      });

      this._cardTypeoption = [
        {value: '', label: '请选择'},
        {value: 'A1', label: 'A1'},
        {value: 'A2', label: 'A2'},
        {value: 'A4', label: 'A4'},
        {value: 'T', label: 'T'},
        {value: 'T1', label: 'T1'},
        {value: 'T2', label: 'T2'},
        {value: 'T3', label: 'T3'},
        {value: '监察A类', label: '监察A类'},
        {value: '监察B类', label: '监察B类'},
        {value: '其他', label: '其他'},
      ];
    }

    this.httpServcie.registerRoleList(this.user.partyType).subscribe(data => {
      if (data.status == '200') {
        this._useroptions = data.data;
      }
    });

    //查询单位全称
    if (this.user) {
      let userList = [];
      userList.push(this.user);
      this.partyList = userList;
      if (this.user.partyId) {
        this.personalBean.partyId = this.user.partyId;
      }
    }

    //查询机构下的角色类型
    this.partyListChange();
  }

  ChangType() {
    if (this.personalBean.roleId == '7') {
      this._cardTypeoption = [
        { value: "T", label: "T" },
        { value: "T1", label: "T1" },
        { value: "T2", label: "T2" }
      ];
    }
    if (this.personalBean.roleId == '5' || this.personalBean.roleId == '6') {
      this._cardTypeoption = [
        { value: "A4", label: "A4" },
        { value: "其他", label: "其他" }
      ];
    }
    if ( this.personalBean.roleId == '6') {
      this._cardTypeoption = [
        { value: "T3", label: "T3" },
        { value: "其他", label: "其他" }
      ];
    }
    if (this.personalBean.roleId == '3'
      || this.personalBean.roleId == '4'
      || this.personalBean.roleId == '18') {
      this._cardTypeoption = [
        { value: "监察A类", label: "监察A类" },
        { value: "监察B类", label: "监察B类" },
        { value: "监察协管员证", label: "监察协管员证" },
        { value: "其他", label: "其他" }
      ];
    }
    if (this.personalBean.roleId == '16') {
      this._cardTypeoption = [
        { value: "A1", label: "A1" },
        { value: "A2", label: "A2" },
        { value: "A4", label: "A4" },
        { value: "T3", label: "T3" },
        { value: "其他", label: "其他" }
      ];
    }

    if (this.personalBean.roleId == '17'){
      this._cardTypeoption = [
        { value: "T", label: "T" },
        { value: "T1", label: "T1" },
        { value: "T2", label: "T2" },
        { value: "其他", label: "其他" }
      ];
    }

    if (this.personalBean.roleId == '8') {
      this._cardTypeoption = [
        { value: "电梯检验员证", label: "电梯检验员证" },
        { value: "电梯检验师证", label: "电梯检验师证" }
      ];
    }
    if (this.personalBean.roleId == '19') {
      this._cardTypeoption = [
        { value: "电梯检验员证", label: "电梯检验员证" },
        { value: "电梯检验师证", label: "电梯检验师证" },
        { value: "其他", label: "其他" }
      ];
    }
  }

  ngOnChanges() {
  }

  submitForm($event) {
    //校验是否能提交
    //没有填的标红
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
    }
    //处理是否提交
    for (const i in this.validateForm.controls) {
      if(!this.validateForm.controls[i].valid){
        return;
      }
    }
    for (let role of this._useroptions) {
      if (this.personalBean.roleId == role.id) {
        this.personalBean.roleName = role.roleName;
        break;
      }
    }
    // 资质证书附件
    this.personalBean.fileList=null;
    if(this.fileList.length>0){
      this.fileList.forEach(element=>{
        this.personalBean.fileList=element['response']['data'];
      });
      if (!this.personalBean.firstgtshow) {
        this._notification.create('error', '失败提示', '请输入初次取证时间');
        return;
      }
    }

    //社保证明附件
    if (this.socialList.length > 0) {
      let files = "";
      this.socialList.forEach(element => {
        files += (element["response"]["data"])+",";
      });
      this.personalBean.socialList = files;
    }

    if (this.personalBean.firstgtshow) {
      this.personalBean.firstgt = moment(this.personalBean.firstgtshow).format('YYYYMMDD');
    }
    // 判断是数组还是字符串

    if (this.cardType != null && this.cardType.length > 0) {
      this.personalBean.cardType = this.cardType.join(',');
    }


    // 获取
    this.personalBean.partyType = JSON.parse(window.localStorage["user"]).partyType;

    console.log(this.personalBean)
    this.isSpinning = true;
    let ob = this.httpServcie.addUser(this.personalBean);
    ob.subscribe((data)=>{
      this.isSpinning = false;
      if(data.status==200){
        this._notification.create('success', '成功提示', '新增成功');
        this.outPut.emit($event);
      }else{
        this._notification.create('error', '失败提示', data.message);
        return;
      }
    })
  }

  //选择单位
  partyListChange(){
    if(this.user.partyId){
      this.httpServcie.registRoleTypeList(this.user.partyId).subscribe(data=>{
        if(data.status=='200'){
          this.roleTypeList = data.data;
          //如果用户有角色类型就回显
          if(this.user.roleTypeId){
            this.personalBean.roleTypeId = this.user.roleTypeId;
          }
        }
      })
    }else{
      this.roleTypeList=[{roleTypeName:'请选择',id:''}];
      this.personalBean.roleTypeId='';
      this.roleTypeChange();
    }
  }

  //用户姓名校验
  userNameCheck = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return {required: true};
    }else if (control.value){
      let reg =/^[\u4e00-\u9fa5]{2,5}$/;
      if (!reg.test(control.value)) {
        return { checkFormat: true, error: true };
      }
    }
  }

  //选择角色类型
  roleTypeChange(){
    if(this.personalBean.roleTypeId){
      this.httpServcie.registerRoleList(this.user.partyType).subscribe(data=>{
        if(data.status=='200'){
          this._useroptions = data.data;
        }
      })
    }else{
      //查询机构下的所有角色
      this._useroptions=[{roleName:'请选择',id:''}];
      this.personalBean.roleId='';
    }
  }

  //确认密码校验
  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls["password"].value) {
      return { confirm: true, error: true };
    }
  };

  // 身份证号码校验
  cardNumberCheck = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value) {
      let reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
      if (!reg.test(control.value)) {
        return { checkFormat: true, error: true };
      }
    }
  };

  //交验
  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  //手机号码校验
  mobileCheck = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value) {
      let reg = /^1[0-9]{10}$/;
      if (!reg.test(control.value)) {
        return { checkMobile: true, error: true };
      }
    }
  };

  //文件上传
  previewImage = '';
  previewVisible = false;
  fileList:UploadFile[] = [];

  //查看
  handlePreview = (file: UploadFile) => {

    this.previewImage =this.config.IP+this.config.API.getUpload+"/"+file['response']['data'] || file.thumbUrl;
    this.previewVisible = true;
  }
}
